package com.sendpo.zjx.sendpo.activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.FriendCircleDomain;
import com.sendpo.zjx.sendpo.domain.UserActiveInfoDomain;
import com.sendpo.zjx.sendpo.domain.UserFriendCircleCommentDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.KeyBoardUtils;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;
import com.sendpo.zjx.sendpo.views.MainScrollview;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import me.shaohui.bottomdialog.BottomDialog;

public class UserActiveInfoActvitiy extends AppCompatActivity {


    @BindView(R.id.share_bt)
    RelativeLayout shareBt;
    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.send_bt)
    Button sendBt;
    @BindView(R.id.editer_iv)
    ImageView editerIv;
    @BindView(R.id.content_edit)
    EditText contentEdit;
    @BindView(R.id.bottom)
    RelativeLayout bottom;
    @BindView(R.id.head_icon)
    CircleImageView headIcon;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.datetime)
    TextView datetime;
    @BindView(R.id.location)
    TextView location;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.text)
    WebView text;
    @BindView(R.id.imgs)
    LinearLayout imgs;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.queryall_guest)
    RelativeLayout queryallGuest;
    @BindView(R.id.maincrollview)
    MainScrollview maincrollview;
    private int currentlastitem = 0;
    private FriendCircleDomain.DataBean dataBean = null;
    private RecylcerAdaper adpter;
    private boolean lastloading = false;
    private LinearLayoutManager lm = null;
    private int pagenow = 1;
    private Tencent tencent;
    private BottomDialog bottomDialog;
    private int id = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_useractiveinfo);
        Tools.initStatus(this, R.color.black);
        ButterKnife.bind(this);
        lm=new LinearLayoutManager(this,OrientationHelper.VERTICAL,false){
            @Override
            public boolean canScrollVertically() {
                return  false;
            }
        };

        recyclerview.setLayoutManager(lm);
        this.dataBean = ((FriendCircleDomain.DataBean) getIntent().getSerializableExtra("data"));
        if (this.dataBean != null) {
            this.id = this.dataBean.getUserFriendscircleId();
            initInfo(this.id + "");
            this.pagenow = 1;
            addWatch(id + "");
            pagenow = 1;
            query(pagenow, id);

        }
        maincrollview.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()){
                    case MotionEvent.ACTION_MOVE:
                        int scrollY=view.getScrollY();
                        int height=view.getHeight();
                        int scrollViewMeasuredHeight=maincrollview.getChildAt(0).getMeasuredHeight();
                        if(scrollY==0){
                            System.out.println("*******************滑动到了顶端 view.getScrollY()="+scrollY);
                        }
                        if((scrollY+height)==scrollViewMeasuredHeight){
                            if(adpter!=null&&adpter.dataBeen.size()>=10&&lastloading==false){
                                pagenow++;
                                append(pagenow,id);

                            }

                        }
                        break;
                }
                return false;
            }
        });
    }

    public void initComponent() {
        this.lm = new LinearLayoutManager(this, 1, false) {
            public boolean canScrollVertically() {
                return false;
            }
        };
        this.recyclerview.setLayoutManager(this.lm);
        initShare();
    }

    @OnClick({R.id.backbt, R.id.send_bt})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;
            case R.id.send_bt:
                List<User> userList = Xutils.queryAll(getApplication(), User.class);
                if ((userList == null) || (userList.size() == 0)) {
                    Tools.redirectActivity(this, LoginActivity.class);
                    return;
                }
                if (TextUtils.isEmpty(this.contentEdit.getText().toString().trim())) {
                    Toast.makeText(getApplicationContext(), "评论不能空", Toast.LENGTH_SHORT).show();
                    return;
                }
                addGuest(this.id + "", ((User) userList.get(0)).getUserId() + "", this.contentEdit.getText().toString().trim());
                this.contentEdit.getText().clear();
                KeyBoardUtils.closeKeybord(contentEdit, this);
                return;
        }
    }

    private void onClickQQShare() {
        Bundle localBundle = new Bundle();
        localBundle.putString("appName", getResources().getString(R.string.app_name));
        localBundle.putString("title", "产品标题");
        localBundle.putString("summary", "产品描述");
        localBundle.putString("targetUrl", "http://www.baidu.com");
        localBundle.putString("imageUrl", "http://images.3158.cn/data/attachment/tougao/article/2015/12/17/df0b92921cb9fa8bb4f82c18ad1e08ba.jpg");
        localBundle.putInt("req_type", 1);
        localBundle.putInt("cflag", 2);
        this.tencent.shareToQQ(this, localBundle, new QQShareUiListener());
    }

    private void shareToQzone() {
        Bundle localBundle = new Bundle();
        localBundle.putString("appName", getResources().getString(R.string.app_name));
        localBundle.putString("title", "产品标题");
        localBundle.putString("summary", "产品描述");
        localBundle.putString("targetUrl", "http://wapi.jiechennuo.com/wifijz.apk");
        localBundle.putInt("req_type", 1);
        ArrayList localArrayList = new ArrayList();
        localArrayList.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1491909596292&di=8d177470e12744ff9eba0f7f55a89c78&imgtype=0&src=http%3A%2F%2Fwww.pp3.cn%2Fuploads%2F201611%2F2016120301.jpg");
        localBundle.putStringArrayList("imageUrl", localArrayList);
        this.tencent.shareToQzone(this, localBundle, new QQShareUiListener());
    }

    public void initShare() {
        this.bottomDialog = BottomDialog.create(getSupportFragmentManager());
        this.bottomDialog.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                v.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View paramAnonymous2View) {
                        UserActiveInfoActvitiy.this.bottomDialog.dismiss();
                    }
                });

                v.findViewById(R.id.qqspace_bt).setOnClickListener(new View.OnClickListener() {
                    public void onClick(View paramAnonymous2View) {
                        UserActiveInfoActvitiy.this.shareToQzone();
                    }
                });
                v.findViewById(R.id.qq_bt).setOnClickListener(new View.OnClickListener() {
                    public void onClick(View paramAnonymous2View) {
                        UserActiveInfoActvitiy.this.onClickQQShare();
                    }
                });
                v.findViewById(R.id.closebt).setOnClickListener(new View.OnClickListener() {
                    public void onClick(View paramAnonymous2View) {
                        UserActiveInfoActvitiy.this.bottomDialog.dismiss();
                    }
                });
            }
        });

        this.bottomDialog.setLayoutRes(R.layout.layout_dialog_share);
        this.bottomDialog.setDimAmount(0.5F);
        this.bottomDialog.setCancelOutside(true);
        this.bottomDialog.setTag("BottomDialog");
        this.tencent = Tencent.createInstance(HttpUrl.QQ_KEY, getApplicationContext());
    }

    private class QQShareUiListener implements IUiListener {
        private QQShareUiListener() {
        }

        public void onCancel() {
        }

        public void onComplete(Object paramObject) {
            System.out.println("********" + paramObject.toString());
        }

        public void onError(UiError paramUiError) {
            Toast.makeText(UserActiveInfoActvitiy.this.getApplicationContext().getApplicationContext(), paramUiError.errorDetail, Toast.LENGTH_SHORT).show();
        }
    }


    public class RecylcerAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        public List<UserFriendCircleCommentDomain.DataBean> dataBeen;
        public LayoutInflater inflater;

        public RecylcerAdaper(Context context, List<UserFriendCircleCommentDomain.DataBean> dataBeen) {
            this.inflater = LayoutInflater.from(context);
            this.dataBeen = dataBeen;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new IndexHoler(this.inflater.inflate(R.layout.layout_userguest_listitem, parent, false));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            final IndexHoler ih = (IndexHoler) holder;
            final UserFriendCircleCommentDomain.DataBean localDataBean = this.dataBeen.get(position);

            Glide.with(UserActiveInfoActvitiy.this)
                    .load("" + localDataBean.getUserAvatarpath())
                    .asBitmap()
                    .placeholder(R.drawable.nim_avatar_default)
                    .centerCrop()
                    .animate(R.anim.fade_in)
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            ih.cir_icon.setImageBitmap(resource);
                        }
                    });
            ih.cir_icon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String, Object> map = new HashMap();
                    map.put("id", Integer.valueOf(localDataBean.getUserId()));
                    Tools.redirectActivity(UserActiveInfoActvitiy.this, UserPersonCenterActivity.class, map);
                }
            });

            ih.name.setText("" + localDataBean.getUserName());
            if (!TextUtils.isEmpty(localDataBean.getCommentsCreatetime())) {
                ih.dateitme.setText(new SimpleDateFormat("yyyy年MM月dd日").format(Tools.getStringtoDate(localDataBean.getCommentsCreatetime(), "yyyy-MM-dd HH:mm:ss")) + "");
            }
            ih.content.setText("" + localDataBean.getCommentText());
        }

        @Override
        public int getItemCount() {
            return dataBeen.size();
        }

        public void delete(int paramInt) {
            this.dataBeen.remove(paramInt);
            notifyDataSetChanged();
        }

        public void initAppend(List<UserFriendCircleCommentDomain.DataBean> paramList) {
            this.dataBeen.addAll(paramList);
            notifyDataSetChanged();
        }

        public void initRefresh(List<UserFriendCircleCommentDomain.DataBean> paramList) {
            this.dataBeen.removeAll(this.dataBeen);
            this.dataBeen.addAll(paramList);
            notifyDataSetChanged();
        }


        public class IndexHoler extends RecyclerView.ViewHolder {
            public CircleImageView cir_icon;
            public TextView content;
            public TextView dateitme;
            public TextView name;
            public View rootView;

            public IndexHoler(View paramView) {
                super(paramView);
                this.rootView = paramView;
                this.cir_icon = paramView.findViewById(R.id.cir_icon);
                this.name = paramView.findViewById(R.id.name);
                this.dateitme = paramView.findViewById(R.id.dateitme);
                this.content = paramView.findViewById(R.id.content);
            }
        }
    }

    public void initInfo(String id) {
        Map<String, String> map = new HashMap<>();
        map.put("userFriendscircleId", id);
        Xutils.POST(HttpUrl.usefriendcircleByfriendId, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("******************************result" + result);
                Gson gson = new Gson();
                UserActiveInfoDomain domain = gson.fromJson(result, UserActiveInfoDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        UserActiveInfoDomain.DataBean data = domain.getData();
                        Glide.with(UserActiveInfoActvitiy.this)
                                .load(data.getUseravatar())
                                .asBitmap()
                                .animate(R.anim.fade_in)
                                .placeholder(R.drawable.nim_avatar_default)
                                .override(500, 500)
                                .into(new SimpleTarget<Bitmap>() {
                                    @Override
                                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                        UserActiveInfoActvitiy.this.headIcon.setImageBitmap(resource);
                                    }
                                });
                        UserActiveInfoActvitiy.this.name.setText(data.getUsername());
                        UserActiveInfoActvitiy.this.datetime.setText("" + data.getUserFriendscircleCreatedate());
                        UserActiveInfoActvitiy.this.location.setText("" + data.getUserArea());
                        UserActiveInfoActvitiy.this.title.setText("" + data.getUserFriendscircleTag());
                        UserActiveInfoActvitiy.this.text.loadDataWithBaseURL("", "" + data.getUserFriendscircleText(), "text/html", "utf-8", "");
                        if (data.getImgs() != null && data.getImgs().size() != 0) {
                            for (int i = 0; i < data.getImgs().size(); i++) {
                                ImageView localImageView = new ImageView(UserActiveInfoActvitiy.this);
                                localImageView.setLayoutParams(new LinearLayout.LayoutParams(-2, -2));
                                Glide.with(UserActiveInfoActvitiy.this).load("" + (String) data.getImgs().get(i)).asBitmap()
                                        .animate(R.anim.fade_in)
                                        .placeholder(getResources().getColor(R.color.default_lightgray))
                                        .into(localImageView);
                                UserActiveInfoActvitiy.this.imgs.addView(localImageView);
                            }
                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void addWatch(String id) {
        HashMap localHashMap = new HashMap();
        localHashMap.put("userFriendscircleId", "" + id);
        Xutils.POST(HttpUrl.usefriendcirclewatchinfoadd, localHashMap, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    public void addGuest(String userFriendscircleId, String userId, String Text) {
        HashMap localHashMap = new HashMap();
        localHashMap.put("userId", "" + userId);
        localHashMap.put("userFriendscircleId", "" + userFriendscircleId);
        localHashMap.put("Text", Text);
        Xutils.POST(HttpUrl.friendcirclescommentsAdd, localHashMap, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject json = new JSONObject(result);
                    Toast.makeText(UserActiveInfoActvitiy.this.getApplicationContext(), json.getString("message"), Toast.LENGTH_SHORT).show();
                    switch (json.getInt("state")) {
                        case HttpCode.SUCCESS:
                            pagenow = 1;
                            query(pagenow, id);
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(UserActiveInfoActvitiy.this.getApplicationContext(), "请稍后重试", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    public void query(int pagenow, final int userFriendscircleId) {
        HashMap localHashMap = new HashMap();
        localHashMap.put("pagenow", pagenow + "");
        localHashMap.put("userFriendscircleId", userFriendscircleId + "");
        Xutils.POST(HttpUrl.friendcirclescommentsQuery, localHashMap, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("******************************friendcirclescommentsQuery"+result);

                Gson gson = new Gson();
                UserFriendCircleCommentDomain domain = gson.fromJson(result, UserFriendCircleCommentDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            System.out.println("******************************friendcirclescommentsQuery"+domain.getData().size());
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(UserActiveInfoActvitiy.this, domain.getData()));
                                recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
                                    @Override
                                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                        super.onScrollStateChanged(recyclerView, newState);
                                        if (currentlastitem == lm.getItemCount() - 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                                            if (UserActiveInfoActvitiy.this.pagenow == 1 && adpter.dataBeen.size() >= 10 && lastloading == false) {
                                                UserActiveInfoActvitiy.this.pagenow++;
                                                append(UserActiveInfoActvitiy.this.pagenow, userFriendscircleId);
                                            }
                                        }
                                    }

                                    @Override
                                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                        super.onScrolled(recyclerView, dx, dy);
                                        currentlastitem = lm.findLastVisibleItemPosition();
                                    }
                                });
                            } else {
                                adpter.initRefresh(domain.getData());
                            }

                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    public void append(int pagenow, final int userFriendscircleId) {
        HashMap localHashMap = new HashMap();
        localHashMap.put("pagenow", pagenow + "");
        localHashMap.put("userFriendscircleId", userFriendscircleId + "");
        Xutils.POST(HttpUrl.friendcirclescommentsQuery, localHashMap, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                UserFriendCircleCommentDomain domain = gson.fromJson(result, UserFriendCircleCommentDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(UserActiveInfoActvitiy.this, domain.getData()));
                                recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
                                    @Override
                                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                        super.onScrollStateChanged(recyclerView, newState);
                                        if (currentlastitem == lm.getItemCount() - 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                                            if (UserActiveInfoActvitiy.this.pagenow == 1 && adpter.dataBeen.size() >= 10 && lastloading == false) {
                                                UserActiveInfoActvitiy.this.pagenow++;
                                                append(UserActiveInfoActvitiy.this.pagenow, userFriendscircleId);
                                            }
                                        }
                                    }

                                    @Override
                                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                        super.onScrolled(recyclerView, dx, dy);
                                        currentlastitem = lm.findLastVisibleItemPosition();
                                    }
                                });
                            } else {
                                adpter.initAppend(domain.getData());
                            }

                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


}


